package com.gouda.temporary.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CacheUtils {

    private static final Logger log = LoggerFactory.getLogger(CacheUtils.class);

    private static volatile AccessToken cacheToken = new AccessToken();

    /**
     * 获取微信AccessToken
     * @return AccessToken
     */
    public static String getCachedAccessToken() {
        if (cacheToken.getKey() == null || cacheToken.getCachedTime() < System.currentTimeMillis()) {
            initCacheToken(OpenWxUtils.getAccessToken(), System.currentTimeMillis() + 7000 * 1000);
        }

        log.info(">>>>>>>>>>>>>>>>>>>> accessToken: {}", cacheToken);

        return cacheToken.getKey();
    }

    private static void initCacheToken(String accessToken, long cacheTime) {
        if (accessToken == null) {
            return ;
        }
        cacheToken = new AccessToken(accessToken, cacheTime);
    }


    private static class AccessToken {

        private String key;

        private long cachedTime;

        public AccessToken() {
        }

        public AccessToken(String key, long cacheTime) {
            this.key = key;
            this.cachedTime = cacheTime;
        }

        public long getCachedTime() {
            return cachedTime;
        }

        public String getKey() {
            return key;
        }

        @Override
        public String toString() {
            return "key=" + key + ", cachedTime=" + cachedTime;
        }
    }
}
